package setting

import "github.com/spf13/viper"

type Database struct {
	DbType          string
	SkipMigrations  bool
	DSN             string
	DbName          string
	MaxOpenConn     int
	MaxIdleConn     int
	ConnMaxLifeTime int
}
type RedisConfig struct {
	NetWork  string
	Address  string
	User     string
	Password string
	Database string
}

func (cfg *Cfg) loadDatabase(viper *viper.Viper) error {
	cfgDataBase := viper.Sub("database")
	cfg.DbCfg = Database{
		DbType:          cfgDataBase.GetString("dbType"),
		SkipMigrations:  cfgDataBase.GetBool("SkipMigrations"),
		DSN:             cfgDataBase.GetString("dsn"),
		DbName:          cfgDataBase.GetString("dbName"),
		MaxOpenConn:     cfgDataBase.GetInt("maxOpenConn"),
		MaxIdleConn:     cfgDataBase.GetInt("maxIdleConn"),
		ConnMaxLifeTime: cfgDataBase.GetInt("connMaxlifetime"),
	}
	// 集群模式下，需要加载redis配置
	if cfg.Application.Deploy == DeployType {
		cfgRedis := viper.Sub("redis")
		cfg.RedisConfig = &RedisConfig{
			NetWork:  cfgRedis.GetString("network"),
			Address:  cfgRedis.GetString("address"),
			Password: cfgRedis.GetString("password"),
			Database: cfgRedis.GetString("database"),
		}
	}
	return nil
}
